#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
状态模式 (State Pattern) - Python实现详解

概述引导：
状态模式允许对象在内部状态改变时改变它的行为，对象看起来好像修改了它的类。
状态模式将状态封装成独立的类，并将动作委托到代表当前状态的对象。

学习要点：
1. 传统状态模式实现
2. 枚举状态模式
3. 状态机实现
4. 异步状态转换

Java对比要点：
- Java需要定义State接口和具体状态类
- Python可以使用枚举和字典简化状态管理
- Python支持动态状态注册
- Python的装饰器可以简化状态转换

关键理解：
状态模式消除复杂的条件语句，Python的动态特性使状态管理更灵活。
"""

from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional, Union, Set, Tuple
from dataclasses import dataclass, field
from enum import Enum, auto
from datetime import datetime, timedelta
import time
import json
import threading
import asyncio
from functools import wraps
import logging
import uuid


# ============= 传统状态模式 =============

class State(ABC):
    """
    状态抽象基类
    
    Java对比：
    - Java需要定义State接口
    - Python使用ABC更灵活
    """
    
    @abstractmethod
    def handle(self, context: 'Context') -> Optional['State']:
        """处理状态逻辑，返回下一个状态或None"""
        pass
    
    def enter(self, context: 'Context'):
        """进入状态时的操作"""
        pass
    
    def exit(self, context: 'Context'):
        """退出状态时的操作"""
        pass
    
    def get_name(self) -> str:
        """获取状态名称"""
        return self.__class__.__name__


class Context:
    """
    上下文类
    
    维护当前状态并委托操作给状态对象
    """
    
    def __init__(self, initial_state: State):
        self._current_state = None
        self._state_history: List[Tuple[str, datetime]] = []
        self.set_state(initial_state)
    
    def set_state(self, state: State):
        """设置当前状态"""
        if self._current_state:
            self._current_state.exit(self)
        
        old_state_name = self._current_state.get_name() if self._current_state else "None"
        self._current_state = state
        
        # 记录状态历史
        self._state_history.append((state.get_name(), datetime.now()))
        
        state.enter(self)
        
        print(f"状态转换: {old_state_name} -> {state.get_name()}")
    
    def get_current_state(self) -> State:
        """获取当前状态"""
        return self._current_state
    
    def handle(self) -> bool:
        """处理当前状态"""
        if self._current_state:
            next_state = self._current_state.handle(self)
            if next_state and next_state != self._current_state:
                self.set_state(next_state)
                return True
        return False
    
    def get_state_history(self) -> List[Tuple[str, datetime]]:
        """获取状态历史"""
        return self._state_history.copy()
    
    def get_current_state_name(self) -> str:
        """获取当前状态名称"""
        return self._current_state.get_name() if self._current_state else "None"


# ============= 自动售货机示例 =============

class VendingMachine(Context):
    """
    自动售货机 - 状态模式应用示例
    
    状态：无硬币、有硬币、商品售出、售罄
    """
    
    def __init__(self):
        self.coin_count = 0
        self.item_count = 5
        self.item_price = 1  # 每个商品1个硬币
        super().__init__(NoCoinState())
    
    def insert_coin(self):
        """投入硬币"""
        print(f"\n投入硬币 (当前硬币数: {self.coin_count})")
        self.coin_count += 1
        self.handle()
    
    def eject_coin(self):
        """退币"""
        print(f"\n退币 (当前硬币数: {self.coin_count})")
        if self.coin_count > 0:
            self.coin_count -= 1
        self.handle()
    
    def turn_crank(self):
        """转动曲柄"""
        print(f"\n转动曲柄 (硬币: {self.coin_count}, 商品: {self.item_count})")
        self.handle()
    
    def dispense(self):
        """分发商品"""
        print(f"\n分发商品 (硬币: {self.coin_count}, 商品: {self.item_count})")
        if self.item_count > 0:
            self.item_count -= 1
            self.coin_count -= self.item_price
        self.handle()
    
    def refill(self, count: int):
        """补充商品"""
        print(f"\n补充商品: {count}个")
        self.item_count += count
        self.handle()
    
    def get_status(self) -> Dict[str, Any]:
        """获取状态信息"""
        return {
            'state': self.get_current_state_name(),
            'coins': self.coin_count,
            'items': self.item_count,
            'item_price': self.item_price
        }


class NoCoinState(State):
    """
    无硬币状态
    """
    
    def handle(self, context: VendingMachine) -> Optional[State]:
        """处理无硬币状态"""
        if context.item_count == 0:
            return SoldOutState()
        elif context.coin_count >= context.item_price:
            return HasCoinState()
        return None
    
    def enter(self, context: VendingMachine):
        print("[无硬币状态] 请投入硬币")
    
    def exit(self, context: VendingMachine):
        print("[无硬币状态] 离开无硬币状态")


class HasCoinState(State):
    """
    有硬币状态
    """
    
    def handle(self, context: VendingMachine) -> Optional[State]:
        """处理有硬币状态"""
        if context.item_count == 0:
            return SoldOutState()
        elif context.coin_count < context.item_price:
            return NoCoinState()
        elif context.coin_count >= context.item_price:
            # 检查是否有转动曲柄的操作（简化处理）
            return SoldState()
        return None
    
    def enter(self, context: VendingMachine):
        print("[有硬币状态] 可以购买商品，请转动曲柄")
    
    def exit(self, context: VendingMachine):
        print("[有硬币状态] 离开有硬币状态")


class SoldState(State):
    """
    商品售出状态
    """
    
    def handle(self, context: VendingMachine) -> Optional[State]:
        """处理售出状态"""
        if context.item_count == 0:
            return SoldOutState()
        elif context.coin_count >= context.item_price:
            return HasCoinState()
        else:
            return NoCoinState()
    
    def enter(self, context: VendingMachine):
        print("[售出状态] 正在分发商品...")
        # 自动分发商品
        if context.item_count > 0 and context.coin_count >= context.item_price:
            context.item_count -= 1
            context.coin_count -= context.item_price
            print(f"商品已分发！剩余商品: {context.item_count}")
    
    def exit(self, context: VendingMachine):
        print("[售出状态] 离开售出状态")


class SoldOutState(State):
    """
    售罄状态
    """
    
    def handle(self, context: VendingMachine) -> Optional[State]:
        """处理售罄状态"""
        if context.item_count > 0:
            if context.coin_count >= context.item_price:
                return HasCoinState()
            else:
                return NoCoinState()
        return None
    
    def enter(self, context: VendingMachine):
        print("[售罄状态] 商品已售完，请等待补货")
        # 退还所有硬币
        if context.coin_count > 0:
            print(f"退还硬币: {context.coin_count}个")
            context.coin_count = 0
    
    def exit(self, context: VendingMachine):
        print("[售罄状态] 离开售罄状态")


# ============= 枚举状态模式 =============

class OrderStatus(Enum):
    """订单状态枚举"""
    PENDING = "pending"
    CONFIRMED = "confirmed"
    PAID = "paid"
    SHIPPED = "shipped"
    DELIVERED = "delivered"
    CANCELLED = "cancelled"
    REFUNDED = "refunded"


class OrderEvent(Enum):
    """订单事件枚举"""
    CONFIRM = "confirm"
    PAY = "pay"
    SHIP = "ship"
    DELIVER = "deliver"
    CANCEL = "cancel"
    REFUND = "refund"


@dataclass
class StateTransition:
    """状态转换定义"""
    from_state: OrderStatus
    event: OrderEvent
    to_state: OrderStatus
    condition: Optional[Callable] = None
    action: Optional[Callable] = None


class OrderStateMachine:
    """
    订单状态机 - 枚举状态模式实现
    
    Python特色：
    - 使用枚举定义状态
    - 字典映射状态转换
    - 支持条件和动作
    """
    
    def __init__(self, order_id: str):
        self.order_id = order_id
        self.current_state = OrderStatus.PENDING
        self.state_history: List[Tuple[OrderStatus, datetime, str]] = []
        self.data: Dict[str, Any] = {}
        
        # 定义状态转换规则
        self.transitions = self._define_transitions()
        
        # 记录初始状态
        self._record_state_change(OrderStatus.PENDING, "订单创建")
    
    def _define_transitions(self) -> List[StateTransition]:
        """定义状态转换规则"""
        return [
            # 从待处理状态
            StateTransition(
                OrderStatus.PENDING, 
                OrderEvent.CONFIRM, 
                OrderStatus.CONFIRMED,
                action=self._on_confirm
            ),
            StateTransition(
                OrderStatus.PENDING, 
                OrderEvent.CANCEL, 
                OrderStatus.CANCELLED,
                action=self._on_cancel
            ),
            
            # 从已确认状态
            StateTransition(
                OrderStatus.CONFIRMED, 
                OrderEvent.PAY, 
                OrderStatus.PAID,
                condition=self._can_pay,
                action=self._on_pay
            ),
            StateTransition(
                OrderStatus.CONFIRMED, 
                OrderEvent.CANCEL, 
                OrderStatus.CANCELLED,
                action=self._on_cancel
            ),
            
            # 从已支付状态
            StateTransition(
                OrderStatus.PAID, 
                OrderEvent.SHIP, 
                OrderStatus.SHIPPED,
                condition=self._can_ship,
                action=self._on_ship
            ),
            StateTransition(
                OrderStatus.PAID, 
                OrderEvent.REFUND, 
                OrderStatus.REFUNDED,
                action=self._on_refund
            ),
            
            # 从已发货状态
            StateTransition(
                OrderStatus.SHIPPED, 
                OrderEvent.DELIVER, 
                OrderStatus.DELIVERED,
                action=self._on_deliver
            ),
            
            # 从已取消状态
            StateTransition(
                OrderStatus.CANCELLED, 
                OrderEvent.REFUND, 
                OrderStatus.REFUNDED,
                condition=self._can_refund_cancelled,
                action=self._on_refund
            ),
        ]
    
    def trigger_event(self, event: OrderEvent, **kwargs) -> bool:
        """触发事件"""
        # 查找适用的转换
        for transition in self.transitions:
            if (transition.from_state == self.current_state and 
                transition.event == event):
                
                # 检查条件
                if transition.condition and not transition.condition(**kwargs):
                    print(f"事件 {event.value} 条件不满足")
                    return False
                
                # 执行动作
                if transition.action:
                    transition.action(**kwargs)
                
                # 转换状态
                old_state = self.current_state
                self.current_state = transition.to_state
                
                self._record_state_change(
                    transition.to_state, 
                    f"事件: {event.value}"
                )
                
                print(f"订单 {self.order_id}: {old_state.value} -> {transition.to_state.value}")
                return True
        
        print(f"无效的状态转换: {self.current_state.value} + {event.value}")
        return False
    
    def _record_state_change(self, state: OrderStatus, reason: str):
        """记录状态变化"""
        self.state_history.append((state, datetime.now(), reason))
    
    def get_available_events(self) -> List[OrderEvent]:
        """获取当前状态下可用的事件"""
        events = []
        for transition in self.transitions:
            if transition.from_state == self.current_state:
                events.append(transition.event)
        return events
    
    def get_state_info(self) -> Dict[str, Any]:
        """获取状态信息"""
        return {
            'order_id': self.order_id,
            'current_state': self.current_state.value,
            'available_events': [e.value for e in self.get_available_events()],
            'data': self.data,
            'history_count': len(self.state_history)
        }
    
    # 条件检查方法
    def _can_pay(self, **kwargs) -> bool:
        """检查是否可以支付"""
        return 'payment_method' in kwargs
    
    def _can_ship(self, **kwargs) -> bool:
        """检查是否可以发货"""
        return 'shipping_address' in kwargs
    
    def _can_refund_cancelled(self, **kwargs) -> bool:
        """检查取消的订单是否可以退款"""
        return self.data.get('payment_received', False)
    
    # 动作执行方法
    def _on_confirm(self, **kwargs):
        """确认订单动作"""
        self.data['confirmed_at'] = datetime.now()
        self.data['confirmed_by'] = kwargs.get('user_id', 'system')
    
    def _on_pay(self, **kwargs):
        """支付动作"""
        self.data['payment_method'] = kwargs.get('payment_method')
        self.data['payment_amount'] = kwargs.get('amount', 0)
        self.data['paid_at'] = datetime.now()
        self.data['payment_received'] = True
    
    def _on_ship(self, **kwargs):
        """发货动作"""
        self.data['shipping_address'] = kwargs.get('shipping_address')
        self.data['tracking_number'] = kwargs.get('tracking_number', f"TN{int(time.time())}")
        self.data['shipped_at'] = datetime.now()
    
    def _on_deliver(self, **kwargs):
        """送达动作"""
        self.data['delivered_at'] = datetime.now()
        self.data['delivered_to'] = kwargs.get('recipient', 'customer')
    
    def _on_cancel(self, **kwargs):
        """取消动作"""
        self.data['cancelled_at'] = datetime.now()
        self.data['cancel_reason'] = kwargs.get('reason', 'user_request')
    
    def _on_refund(self, **kwargs):
        """退款动作"""
        self.data['refunded_at'] = datetime.now()
        self.data['refund_amount'] = kwargs.get('amount', self.data.get('payment_amount', 0))
        self.data['refund_method'] = kwargs.get('method', 'original')


# ============= 状态机装饰器 =============

def state_machine(initial_state: str):
    """
    状态机装饰器 - Python特色实现
    
    自动管理状态转换
    """
    def decorator(cls):
        # 添加状态管理属性
        cls._current_state = initial_state
        cls._state_history = []
        cls._transitions = {}
        
        # 添加状态管理方法
        def get_state(self):
            return self._current_state
        
        def set_state(self, new_state: str, reason: str = ""):
            old_state = self._current_state
            self._current_state = new_state
            self._state_history.append({
                'from': old_state,
                'to': new_state,
                'timestamp': datetime.now(),
                'reason': reason
            })
            print(f"状态转换: {old_state} -> {new_state} ({reason})")
        
        def add_transition(self, from_state: str, to_state: str, 
                          condition: Callable = None, action: Callable = None):
            key = from_state
            if key not in self._transitions:
                self._transitions[key] = []
            self._transitions[key].append({
                'to': to_state,
                'condition': condition,
                'action': action
            })
        
        def transition_to(self, target_state: str, **kwargs) -> bool:
            current = self._current_state
            if current in self._transitions:
                for trans in self._transitions[current]:
                    if trans['to'] == target_state:
                        # 检查条件
                        if trans['condition'] and not trans['condition'](self, **kwargs):
                            return False
                        
                        # 执行动作
                        if trans['action']:
                            trans['action'](self, **kwargs)
                        
                        # 转换状态
                        self.set_state(target_state, kwargs.get('reason', 'transition'))
                        return True
            return False
        
        def get_state_history(self):
            return self._state_history.copy()
        
        # 绑定方法到类
        cls.get_state = get_state
        cls.set_state = set_state
        cls.add_transition = add_transition
        cls.transition_to = transition_to
        cls.get_state_history = get_state_history
        
        return cls
    return decorator


@state_machine('idle')
class MediaPlayer:
    """
    媒体播放器 - 使用状态机装饰器
    """
    
    def __init__(self):
        self.current_track = None
        self.volume = 50
        self.position = 0
        
        # 定义状态转换
        self.add_transition('idle', 'playing', 
                           condition=self._has_track,
                           action=self._start_playback)
        self.add_transition('playing', 'paused',
                           action=self._pause_playback)
        self.add_transition('paused', 'playing',
                           action=self._resume_playback)
        self.add_transition('playing', 'idle',
                           action=self._stop_playback)
        self.add_transition('paused', 'idle',
                           action=self._stop_playback)
    
    def load_track(self, track_name: str):
        """加载音轨"""
        self.current_track = track_name
        print(f"加载音轨: {track_name}")
    
    def play(self):
        """播放"""
        if self.get_state() == 'idle':
            return self.transition_to('playing', reason='用户播放')
        elif self.get_state() == 'paused':
            return self.transition_to('playing', reason='用户恢复播放')
        return False
    
    def pause(self):
        """暂停"""
        if self.get_state() == 'playing':
            return self.transition_to('paused', reason='用户暂停')
        return False
    
    def stop(self):
        """停止"""
        if self.get_state() in ['playing', 'paused']:
            return self.transition_to('idle', reason='用户停止')
        return False
    
    def _has_track(self, **kwargs) -> bool:
        """检查是否有音轨"""
        return self.current_track is not None
    
    def _start_playback(self, **kwargs):
        """开始播放动作"""
        print(f"开始播放: {self.current_track}")
        self.position = 0
    
    def _pause_playback(self, **kwargs):
        """暂停播放动作"""
        print(f"暂停播放: {self.current_track} at {self.position}s")
    
    def _resume_playback(self, **kwargs):
        """恢复播放动作"""
        print(f"恢复播放: {self.current_track} from {self.position}s")
    
    def _stop_playback(self, **kwargs):
        """停止播放动作"""
        print(f"停止播放: {self.current_track}")
        self.position = 0
    
    def get_status(self) -> Dict[str, Any]:
        """获取播放器状态"""
        return {
            'state': self.get_state(),
            'track': self.current_track,
            'volume': self.volume,
            'position': self.position
        }


# ============= 异步状态机 =============

class AsyncStateMachine:
    """
    异步状态机
    
    支持异步状态转换和事件处理
    """
    
    def __init__(self, initial_state: str):
        self.current_state = initial_state
        self.state_handlers: Dict[str, Callable] = {}
        self.transition_handlers: Dict[str, Callable] = {}
        self.event_queue = asyncio.Queue()
        self.running = False
        self.state_history: List[Dict[str, Any]] = []
    
    def register_state_handler(self, state: str, handler: Callable):
        """注册状态处理器"""
        self.state_handlers[state] = handler
    
    def register_transition_handler(self, from_state: str, to_state: str, handler: Callable):
        """注册状态转换处理器"""
        key = f"{from_state}->{to_state}"
        self.transition_handlers[key] = handler
    
    async def transition_to(self, new_state: str, **kwargs) -> bool:
        """异步状态转换"""
        if new_state == self.current_state:
            return True
        
        old_state = self.current_state
        transition_key = f"{old_state}->{new_state}"
        
        # 执行转换处理器
        if transition_key in self.transition_handlers:
            try:
                await self.transition_handlers[transition_key](**kwargs)
            except Exception as e:
                print(f"状态转换失败: {e}")
                return False
        
        # 更新状态
        self.current_state = new_state
        
        # 记录历史
        self.state_history.append({
            'from': old_state,
            'to': new_state,
            'timestamp': datetime.now(),
            'data': kwargs
        })
        
        print(f"异步状态转换: {old_state} -> {new_state}")
        
        # 执行新状态处理器
        if new_state in self.state_handlers:
            try:
                await self.state_handlers[new_state](**kwargs)
            except Exception as e:
                print(f"状态处理器执行失败: {e}")
        
        return True
    
    async def send_event(self, event: str, **kwargs):
        """发送事件"""
        await self.event_queue.put({
            'event': event,
            'timestamp': datetime.now(),
            'data': kwargs
        })
    
    async def start(self):
        """启动状态机"""
        self.running = True
        
        while self.running:
            try:
                # 等待事件
                event_data = await asyncio.wait_for(self.event_queue.get(), timeout=1.0)
                
                # 处理事件
                await self._handle_event(event_data)
                
            except asyncio.TimeoutError:
                # 超时，继续循环
                continue
            except Exception as e:
                print(f"事件处理错误: {e}")
    
    async def stop(self):
        """停止状态机"""
        self.running = False
    
    async def _handle_event(self, event_data: Dict[str, Any]):
        """处理事件"""
        event = event_data['event']
        data = event_data['data']
        
        print(f"处理事件: {event} in state {self.current_state}")
        
        # 这里可以根据当前状态和事件类型决定状态转换
        # 简化实现，实际应用中需要更复杂的逻辑
        if event == 'timeout' and self.current_state == 'waiting':
            await self.transition_to('timeout', **data)
        elif event == 'complete' and self.current_state == 'processing':
            await self.transition_to('completed', **data)
    
    def get_state_info(self) -> Dict[str, Any]:
        """获取状态信息"""
        return {
            'current_state': self.current_state,
            'running': self.running,
            'history_count': len(self.state_history),
            'queue_size': self.event_queue.qsize()
        }


# ============= 演示函数 =============

def demonstrate_traditional_state():
    """
    演示传统状态模式
    
    概述引导：
    展示传统状态模式的实现，包括状态接口、具体状态类
    和上下文类的协作。
    
    学习要点：
    1. 状态接口的定义
    2. 具体状态的实现
    3. 上下文的状态管理
    4. 状态转换逻辑
    
    关键理解：
    状态模式将状态相关的行为封装到独立的状态类中。
    """
    print("=== 传统状态模式演示 ===")
    print("\n学习目标：")
    print("- 理解状态模式的结构")
    print("- 掌握状态的封装和转换")
    print("- 学习状态相关行为的管理")
    print("\n重点概念：")
    print("- 状态的封装")
    print("- 行为随状态变化")
    print("- 状态转换逻辑")
    print("=" * 50)
    
    # 创建自动售货机
    vending_machine = VendingMachine()
    
    print(f"\n初始状态: {vending_machine.get_status()}")
    
    # 模拟购买流程
    print("\n=== 正常购买流程 ===")
    
    # 投入硬币
    vending_machine.insert_coin()
    print(f"状态: {vending_machine.get_status()}")
    
    # 转动曲柄购买
    vending_machine.turn_crank()
    print(f"状态: {vending_machine.get_status()}")
    
    # 再次购买
    print("\n=== 再次购买 ===")
    vending_machine.insert_coin()
    vending_machine.turn_crank()
    print(f"状态: {vending_machine.get_status()}")
    
    # 继续购买直到售罄
    print("\n=== 购买直到售罄 ===")
    for i in range(4):
        print(f"\n第{i+3}次购买:")
        vending_machine.insert_coin()
        vending_machine.turn_crank()
        print(f"状态: {vending_machine.get_status()}")
        
        if vending_machine.item_count == 0:
            break
    
    # 尝试在售罄状态下投币
    print("\n=== 售罄状态下投币 ===")
    vending_machine.insert_coin()
    print(f"状态: {vending_machine.get_status()}")
    
    # 补货
    print("\n=== 补货 ===")
    vending_machine.refill(3)
    print(f"状态: {vending_machine.get_status()}")
    
    # 查看状态历史
    print("\n=== 状态历史 ===")
    history = vending_machine.get_state_history()
    for i, (state, timestamp, _) in enumerate(history[-5:]):
        print(f"{i+1}. {state} at {timestamp.strftime('%H:%M:%S')}")


def demonstrate_enum_state_machine():
    """
    演示枚举状态机
    """
    print("\n=== 枚举状态机演示 ===")
    
    # 创建订单状态机
    order = OrderStateMachine("ORDER-001")
    
    print(f"\n初始状态: {order.get_state_info()}")
    
    # 订单处理流程
    print("\n=== 正常订单流程 ===")
    
    # 确认订单
    success = order.trigger_event(OrderEvent.CONFIRM, user_id="user123")
    print(f"确认订单: {success}")
    print(f"状态: {order.get_state_info()}")
    
    # 支付订单
    success = order.trigger_event(OrderEvent.PAY, 
                                 payment_method="credit_card", 
                                 amount=99.99)
    print(f"\n支付订单: {success}")
    print(f"状态: {order.get_state_info()}")
    
    # 发货
    success = order.trigger_event(OrderEvent.SHIP, 
                                 shipping_address="123 Main St",
                                 tracking_number="TN123456")
    print(f"\n发货: {success}")
    print(f"状态: {order.get_state_info()}")
    
    # 送达
    success = order.trigger_event(OrderEvent.DELIVER, recipient="John Doe")
    print(f"\n送达: {success}")
    print(f"状态: {order.get_state_info()}")
    
    # 测试无效转换
    print("\n=== 无效转换测试 ===")
    success = order.trigger_event(OrderEvent.CANCEL)
    print(f"尝试取消已送达订单: {success}")
    
    # 创建另一个订单测试取消流程
    print("\n=== 取消订单流程 ===")
    order2 = OrderStateMachine("ORDER-002")
    
    order2.trigger_event(OrderEvent.CONFIRM, user_id="user456")
    order2.trigger_event(OrderEvent.PAY, payment_method="paypal", amount=149.99)
    
    print(f"\n订单2支付后状态: {order2.get_state_info()}")
    
    # 申请退款
    success = order2.trigger_event(OrderEvent.REFUND, amount=149.99, method="original")
    print(f"申请退款: {success}")
    print(f"最终状态: {order2.get_state_info()}")
    
    # 显示订单数据
    print(f"\n订单1数据: {order.data}")
    print(f"订单2数据: {order2.data}")


def demonstrate_decorator_state_machine():
    """
    演示装饰器状态机
    """
    print("\n=== 装饰器状态机演示 ===")
    
    # 创建媒体播放器
    player = MediaPlayer()
    
    print(f"\n初始状态: {player.get_status()}")
    
    # 尝试播放（没有音轨）
    print("\n=== 无音轨播放测试 ===")
    success = player.play()
    print(f"播放结果: {success}")
    print(f"状态: {player.get_status()}")
    
    # 加载音轨并播放
    print("\n=== 正常播放流程 ===")
    player.load_track("Song1.mp3")
    
    success = player.play()
    print(f"播放结果: {success}")
    print(f"状态: {player.get_status()}")
    
    # 暂停
    success = player.pause()
    print(f"\n暂停结果: {success}")
    print(f"状态: {player.get_status()}")
    
    # 恢复播放
    success = player.play()
    print(f"\n恢复播放结果: {success}")
    print(f"状态: {player.get_status()}")
    
    # 停止
    success = player.stop()
    print(f"\n停止结果: {success}")
    print(f"状态: {player.get_status()}")
    
    # 查看状态历史
    print("\n=== 状态历史 ===")
    history = player.get_state_history()
    for i, record in enumerate(history):
        print(f"{i+1}. {record['from']} -> {record['to']} ({record['reason']}) at {record['timestamp'].strftime('%H:%M:%S')}")


async def demonstrate_async_state_machine():
    """
    演示异步状态机
    """
    print("\n=== 异步状态机演示 ===")
    
    # 创建异步状态机
    async_sm = AsyncStateMachine('idle')
    
    # 注册状态处理器
    async def idle_handler(**kwargs):
        print("进入空闲状态")
        await asyncio.sleep(0.1)
    
    async def processing_handler(**kwargs):
        print(f"开始处理任务: {kwargs.get('task_id', 'unknown')}")
        await asyncio.sleep(0.5)  # 模拟处理时间
    
    async def completed_handler(**kwargs):
        print(f"任务完成: {kwargs.get('result', 'success')}")
    
    async def timeout_handler(**kwargs):
        print("任务超时")
    
    # 注册处理器
    async_sm.register_state_handler('idle', idle_handler)
    async_sm.register_state_handler('processing', processing_handler)
    async_sm.register_state_handler('completed', completed_handler)
    async_sm.register_state_handler('timeout', timeout_handler)
    
    # 注册转换处理器
    async def start_processing_transition(**kwargs):
        print("准备开始处理...")
        await asyncio.sleep(0.1)
    
    async def complete_transition(**kwargs):
        print("处理完成，清理资源...")
        await asyncio.sleep(0.1)
    
    async_sm.register_transition_handler('idle', 'processing', start_processing_transition)
    async_sm.register_transition_handler('processing', 'completed', complete_transition)
    
    # 启动状态机（在后台运行）
    state_machine_task = asyncio.create_task(async_sm.start())
    
    print(f"\n初始状态: {async_sm.get_state_info()}")
    
    # 模拟异步状态转换
    print("\n=== 异步状态转换 ===")
    
    # 开始处理
    await async_sm.transition_to('processing', task_id='TASK-001')
    await asyncio.sleep(0.2)
    
    # 发送完成事件
    await async_sm.send_event('complete', result='success')
    await asyncio.sleep(0.2)
    
    # 回到空闲状态
    await async_sm.transition_to('idle')
    await asyncio.sleep(0.1)
    
    # 测试超时场景
    print("\n=== 超时场景测试 ===")
    await async_sm.transition_to('processing', task_id='TASK-002')
    await async_sm.transition_to('timeout', reason='processing_timeout')
    
    print(f"\n最终状态: {async_sm.get_state_info()}")
    
    # 停止状态机
    await async_sm.stop()
    state_machine_task.cancel()
    
    try:
        await state_machine_task
    except asyncio.CancelledError:
        print("异步状态机已停止")


def demonstrate_java_comparison():
    """
    Java对比演示
    
    Java等价代码：
    ```java
    // Java版本的状态模式
    public interface State {
        void handle(Context context);
        void enter(Context context);
        void exit(Context context);
        String getName();
    }
    
    public class ConcreteStateA implements State {
        @Override
        public void handle(Context context) {
            // 处理逻辑
            if (someCondition) {
                context.setState(new ConcreteStateB());
            }
        }
        
        @Override
        public void enter(Context context) {
            System.out.println("Entering State A");
        }
        
        @Override
        public void exit(Context context) {
            System.out.println("Exiting State A");
        }
        
        @Override
        public String getName() {
            return "StateA";
        }
    }
    
    public class Context {
        private State currentState;
        
        public Context(State initialState) {
            setState(initialState);
        }
        
        public void setState(State state) {
            if (currentState != null) {
                currentState.exit(this);
            }
            currentState = state;
            state.enter(this);
        }
        
        public void handle() {
            currentState.handle(this);
        }
    }
    
    // 使用
    Context context = new Context(new ConcreteStateA());
    context.handle();
    ```
    
    Python优势：
    1. 枚举简化状态定义
    2. 装饰器自动状态管理
    3. 异步状态转换支持
    4. 更灵活的状态机配置
    """
    print("\n=== Java对比说明 ===")
    print("\nPython优势：")
    print("1. 枚举简化状态定义")
    print("2. 装饰器自动状态管理")
    print("3. 异步状态转换支持")
    print("4. 更灵活的状态机配置")
    print("5. 字典映射状态转换")
    
    print("\nJava特点：")
    print("1. 强类型的状态接口")
    print("2. 编译时类型检查")
    print("3. 更明确的状态契约")
    print("4. 更好的IDE支持")
    
    # 演示Python的枚举优势
    print("\n=== Python枚举状态演示 ===")
    
    # 简单的状态枚举
    class SimpleState(Enum):
        INIT = "init"
        RUNNING = "running"
        PAUSED = "paused"
        STOPPED = "stopped"
    
    # 状态转换映射
    transitions = {
        SimpleState.INIT: [SimpleState.RUNNING],
        SimpleState.RUNNING: [SimpleState.PAUSED, SimpleState.STOPPED],
        SimpleState.PAUSED: [SimpleState.RUNNING, SimpleState.STOPPED],
        SimpleState.STOPPED: [SimpleState.INIT]
    }
    
    current_state = SimpleState.INIT
    print(f"当前状态: {current_state.value}")
    print(f"可转换到: {[s.value for s in transitions[current_state]]}")
    
    # 状态转换
    if SimpleState.RUNNING in transitions[current_state]:
        current_state = SimpleState.RUNNING
        print(f"转换后状态: {current_state.value}")
        print(f"可转换到: {[s.value for s in transitions[current_state]]}")


def performance_comparison():
    """
    性能对比测试
    """
    print("\n=== 性能对比 ===")
    
    # 测试传统状态模式性能
    print("\n传统状态模式性能测试:")
    vending_machine = VendingMachine()
    
    start_time = time.time()
    for i in range(1000):
        vending_machine.insert_coin()
        vending_machine.turn_crank()
        if vending_machine.item_count == 0:
            vending_machine.refill(1)
    
    traditional_time = time.time() - start_time
    print(f"传统状态模式 (1000次操作): {traditional_time:.4f}秒")
    
    # 测试枚举状态机性能
    print("\n枚举状态机性能测试:")
    order = OrderStateMachine("PERF-TEST")
    
    start_time = time.time()
    for i in range(1000):
        # 重置订单状态
        order.current_state = OrderStatus.PENDING
        
        # 执行状态转换
        order.trigger_event(OrderEvent.CONFIRM, user_id=f"user{i}")
        order.trigger_event(OrderEvent.PAY, payment_method="test", amount=10.0)
        order.trigger_event(OrderEvent.SHIP, shipping_address="test address")
        order.trigger_event(OrderEvent.DELIVER, recipient="test user")
    
    enum_time = time.time() - start_time
    print(f"枚举状态机 (1000次完整流程): {enum_time:.4f}秒")
    
    # 测试装饰器状态机性能
    print("\n装饰器状态机性能测试:")
    player = MediaPlayer()
    player.load_track("test.mp3")
    
    start_time = time.time()
    for i in range(1000):
        player.play()
        player.pause()
        player.play()
        player.stop()
    
    decorator_time = time.time() - start_time
    print(f"装饰器状态机 (1000次播放循环): {decorator_time:.4f}秒")
    
    print(f"\n性能对比:")
    print(f"传统状态模式: {traditional_time:.4f}秒")
    print(f"枚举状态机: {enum_time:.4f}秒")
    print(f"装饰器状态机: {decorator_time:.4f}秒")
    
    # 计算相对性能
    baseline = min(traditional_time, enum_time, decorator_time)
    print(f"\n相对性能 (以最快为基准):")
    print(f"传统状态模式: {traditional_time / baseline:.2f}x")
    print(f"枚举状态机: {enum_time / baseline:.2f}x")
    print(f"装饰器状态机: {decorator_time / baseline:.2f}x")


async def main():
    """主函数"""
    demonstrate_traditional_state()
    demonstrate_enum_state_machine()
    demonstrate_decorator_state_machine()
    await demonstrate_async_state_machine()
    demonstrate_java_comparison()
    performance_comparison()


if __name__ == "__main__":
    asyncio.run(main())